package com.example.a2205_fx.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.a2205_fx.R;
import com.example.a2205_fx.adapter.PinglunAdapter;
import com.example.a2205_fx.adapter.VideoAdapter;
import com.example.a2205_fx.base.BaseFragment;
import com.example.a2205_fx.database.AppDataBaseUtil;
import com.example.a2205_fx.databinding.FragmentHomeBinding;
import com.example.a2205_fx.entity.PinglunEntity;
import com.example.a2205_fx.entity.ResultEntity;
import com.example.a2205_fx.entity.VideoEntity;
import com.example.a2205_fx.live.LiveActivity;
import com.example.a2205_fx.util.anno.CheckLogin;
import com.example.a2205_fx.video.VideoViewModel;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMVideo;

import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends BaseFragment<FragmentHomeBinding, VideoViewModel> {
    List<VideoEntity.DataBean> videos = new ArrayList<>();
    VideoAdapter videoAdapter;

    int page = 2;
    int size = 10;
    int index = 0;//视频下标

    List<PinglunEntity.DataBean> pingluns= new ArrayList<>();
    PinglunAdapter pinglunAdapter;

    @Override
    protected void initData() {
        viewModel.success.observe(this, new Observer<VideoEntity>() {
            @Override
            public void onChanged(VideoEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    videos.addAll(entity.getData());
                    videoAdapter.notifyDataSetChanged();
                }
            }
        });
        viewModel.loveSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    ImageView love = (ImageView) videoAdapter.getViewByPosition(index,R.id.iv_xihuan);
                    love.setImageResource(R.drawable.ic_xihuanred);
                    videos.get(index).setDianzan(1);
                    ObjectAnimator scaleX = ObjectAnimator.ofFloat(love, "scaleX", 1, 2, 1);
                    ObjectAnimator scaleY = ObjectAnimator.ofFloat(love, "scaleY", 1, 2, 1);
                    AnimatorSet set = new AnimatorSet();
                    set.setDuration(2000);
                    set.play(scaleX).with(scaleY);
                    set.start();
                }
            }
        });
        viewModel.noloveSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    ImageView love = (ImageView) videoAdapter.getViewByPosition(index,R.id.iv_xihuan);
                    love.setImageResource(R.drawable.ic_xihuan);
                    videos.get(index).setDianzan(0);
                }
            }
        });
        viewModel.getSuccess.observe(this, new Observer<PinglunEntity>() {
            @Override
            public void onChanged(PinglunEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    pingluns.clear();
                    pingluns.addAll(entity.getData());
                    pinglunAdapter.notifyDataSetChanged();
                }
            }
        });
        viewModel.comSucc.observe(this, new Observer<PinglunEntity>() {
            @Override
            public void onChanged(PinglunEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    pingluns.add(0,entity.getData().get(0));
                    pinglunAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected void initView() {
        videoAdapter = new VideoAdapter(videos);
        binding.rv.setAdapter(videoAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        binding.rv.setLayoutManager(linearLayoutManager);

        viewModel.video(page,size);
        binding.smart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                viewModel.video(page,size);
                binding.smart.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 2;
                videos.clear();
                viewModel.video(page,size);
                binding.smart.finishRefresh();
            }
        });
        //滑动分割
        PagerSnapHelper helper = new PagerSnapHelper();
        helper.attachToRecyclerView(binding.rv);
        //滑动自动播放
        binding.rv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int position = linearLayoutManager.findFirstVisibleItemPosition();
                index = position;
                StandardGSYVideoPlayer gsyVideoPlayer = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(position,R.id.gsy);
                if(gsyVideoPlayer!=null){
                    gsyVideoPlayer.startPlayLogic();
                }
            }
        });
        //点赞，取消点赞  收藏
        videoAdapter.addChildClickViewIds(R.id.iv_xihuan,R.id.iv_shoucang,R.id.iv_fenxiang,
                R.id.iv_pinglun,R.id.iv_close,R.id.iv_fasong,R.id.tv_full,R.id.iv_user);
        videoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()){
                    case R.id.iv_xihuan:
                        love(position);
                        break;
                    case R.id.iv_shoucang:
                        shoucang(position);
                        break;
                    case R.id.iv_fenxiang:
                        fenxiang(position);
                        break;
                    case R.id.iv_pinglun:
                        binding.rv.setFlag(false);
                        openPinglun(position);
                        break;
                    case R.id.iv_close:
                        binding.rv.setFlag(true);
                        closePinglun(position);
                        break;
                    case R.id.iv_fasong:
                        sendPinglun(position);
                        break;
                    case R.id.tv_full:
                        full(position);
                        break;
                    case R.id.iv_user:
                        live(position);
                        break;
                }
            }
        });
    }
    //点击头像进入直播间
    @CheckLogin
    private void live(int position) {
        Intent intent = new Intent(getContext(), LiveActivity.class);
        intent.putExtra("index",position);
        startActivity(intent);
    }

    private void full(int position) {
        StandardGSYVideoPlayer gsyVideoPlayer = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(position, R.id.gsy);
        gsyVideoPlayer.startWindowFullscreen(getContext(),true,false);
    }

    private void sendPinglun(int position) {
        //获取评论内容
        EditText et = (EditText) videoAdapter.getViewByPosition(position, R.id.et_pinglun);
        String trim = et.getText().toString().trim();
        if(trim.isEmpty()){
            ToastUtils.showLong("未输入内容");
            return;
        }
        viewModel.comment(trim,videos.get(position).getId());

        et.setText("");
    }

    private void closePinglun(int position) {
        //找到评论框
        ConstraintLayout clPinglun = (ConstraintLayout) videoAdapter.getViewByPosition(position, R.id.cl_pinglun);
        clPinglun.setVisibility(View.GONE);
    }

    private void openPinglun(int position) {
        //找到评论框
        ConstraintLayout clPinglun = (ConstraintLayout) videoAdapter.getViewByPosition(position, R.id.cl_pinglun);
        clPinglun.setVisibility(View.VISIBLE);
        //找到评论列表
        RecyclerView rvPinglun = (RecyclerView) videoAdapter.getViewByPosition(position, R.id.rv_pinglun);
        pinglunAdapter = new PinglunAdapter(R.layout.item_pinglun,pingluns);
        rvPinglun.setAdapter(pinglunAdapter);
        rvPinglun.setLayoutManager(new LinearLayoutManager(getContext()));
        viewModel.getComment(videos.get(position).getId());
    }

    private void fenxiang(int position) {
        UMVideo video =new UMVideo(videos.get(position).getVideopath());
        new ShareAction(getActivity()).withText("hello").withMedia(video)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA media) {

                    }

                    @Override
                    public void onError(SHARE_MEDIA media, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA media) {

                    }
                })
                .open();
    }

    @CheckLogin
    private void shoucang(int position) {
        AppDataBaseUtil.getInstance().getVideoDao().insertVideo(videos.get(position));
        ImageView ivshoucang = (ImageView) videoAdapter.getViewByPosition(position,R.id.iv_shoucang);
        ivshoucang.setImageResource(R.drawable.ic_shoucangyellow);
    }

    @CheckLogin
    private void love(int position) {
        if(videos.get(position).getDianzan()==1){
            viewModel.nolove(videos.get(position).getId());
        }else {
            viewModel.love(videos.get(position).getId());
        }
    }

    @Override
    protected Class<VideoViewModel> getViewModel() {
        return VideoViewModel.class;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume(true);
    }
}